package com.app.Activity;

import java.util.ArrayList;

import ReadWriteXML.CMember;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.ExpandableListContextMenuInfo;
import android.widget.Toast;

import com.app.Controller.NetworkController;
import com.app.Controller.ReadWriteFileController;
import com.app.DTO.AccountDTO;
import com.app.DTO.RoleDTO;
import com.app.Network.Protocol;
import com.app.PhanQuyen.Quyen;
import com.app.Tree.BoardView;
import com.app.outdoor.InvoikeServices.CayThaoLuanInvoike;
import com.app.outdoor.adapter.SubjectAdapter;
import com.app.outdoor.adapter.SubjectList;

public class od_SubjectActivity extends Activity {
	final static String TAG=Protocol.TAG;
	final private int MENU_XEM_CHI_TIET = 2;
	final private int MENU_TAO_CAY_MOI = 3;
	ExpandableListView expSubject;
	//SubjectList subjects;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.od_activity_subject);
		expSubject = (ExpandableListView) findViewById(R.id.expSubject);
		if(CommonUtilities.subjects==null){
			CommonUtilities.subjects = new SubjectList();
			getSubject();
		}
		ExpandableListAdapter adapter = new SubjectAdapter(this, CommonUtilities.subjects);
		expSubject.setAdapter(adapter);
		registerForContextMenu(expSubject);
	}

	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {

		super.onCreateContextMenu(menu, v, menuInfo);
		ExpandableListView.ExpandableListContextMenuInfo info = (ExpandableListView.ExpandableListContextMenuInfo) menuInfo;

		int type = ExpandableListView.getPackedPositionType(info.packedPosition);
		int group = ExpandableListView.getPackedPositionGroup(info.packedPosition);
		int child = ExpandableListView.getPackedPositionChild(info.packedPosition);
		if (type == 1) {
			menu.add(0, 1, 0, "Xem thông tin");
			menu.add(0, MENU_XEM_CHI_TIET, 0, "Xem chi tiết");
		} else {
			menu.add(0, MENU_TAO_CAY_MOI, 0, "Thêm chủ đề");
		}
	}

	public boolean onContextItemSelected(MenuItem menuItem) {
		ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) menuItem.getMenuInfo();
		int groupPos = 0, childPos = 0;
		int type = ExpandableListView.getPackedPositionType(info.packedPosition);
		if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
			groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition);
			childPos = ExpandableListView.getPackedPositionChild(info.packedPosition);
			if (menuItem.getItemId() == MENU_XEM_CHI_TIET) {
				int idCay = CommonUtilities.subjects.getMember(groupPos, childPos).getId();
				Toast.makeText(getBaseContext(), "Chi tiết id=" + idCay, 1).show();
				if (getCay(idCay,od_SubjectActivity.this)) {
					Intent intent = new Intent(getBaseContext(), frmTreeNodeActivity.class);
					startActivity(intent);
				}
			}
		} else if (type == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
			groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition);
			if (menuItem.getItemId() == MENU_TAO_CAY_MOI) {
				final int idNhom = CommonUtilities.subjects.getGroup(groupPos).getId();
				final int idNguoiDung=CommonUtilities.nguoiDung.getId();
				AlertDialog.Builder builder=new AlertDialog.Builder(this);
				final EditText txtNoiDung=new EditText(this);
				builder.setTitle("Tạo thảo luận mới");
				builder.setView(txtNoiDung);
				builder.setNegativeButton("Hủy bỏ", new DialogInterface.OnClickListener() {					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Toast.makeText(getBaseContext(), "cancel", 1).show();
						
					}
				});
				builder.setPositiveButton("Tạo mới", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {				
						Toast.makeText(getBaseContext(), "OK", 1).show();
						String idCay=taoCay(idNhom, idNguoiDung, txtNoiDung.getText().toString()).trim();
						if(idCay==null || idCay.trim().equals("")){
							Log.d(TAG, "Không tạo đc cay mới");
						}else{
							//Gán role thành lập nhóm
							ArrayList<Quyen> ruleList=ReadWriteFileController.readRule(getApplicationContext(), ReadWriteFileController.RULE_BASE_PATH);
							RoleDTO roleSangLapNhom=new RoleDTO("Người sáng lập nhóm", ruleList);		
							NetworkController._peer.getAccount().addRole(roleSangLapNhom);
							
							//gán cây hiện tại
							CommonUtilities.idCayHienTai=Integer.parseInt(idCay);
							
							//Start activity
							Intent i = new Intent(getBaseContext(), frmNhomChoActivity.class);
							i.putExtra(frmTaoNhom.CODE_GROUP_NAME, CommonUtilities.contacts.getGroupByID(idNhom).getTenNhom());
							NetworkController.setGroupName(CommonUtilities.contacts.getGroupByID(idNhom).getTenNhom());
							CommonUtilities.idNhomHienTai=idNhom;
							createMemberFile();								
							startActivity(i);
						}
					}
				});
				builder.create().show();

				
			}

		}

		return super.onContextItemSelected(menuItem);

	}

	private void getSubject() {
		try {
			int idNguoiDung = CommonUtilities.nguoiDung.getId();
			String data = CayThaoLuanInvoike.getSubject(idNguoiDung);
			Log.d("Phu", "Đã lấy subjects data= "+data + "id nd="+idNguoiDung);
			CommonUtilities.subjects.init(data);
			Log.d("Phu", "Đã lấy subjects size= "+CommonUtilities.subjects.getSize());
		} catch (Exception e) {
			Log.d("Phu", "Không thể get đc subjects");
		}
	}

	public static boolean getCay(int idCay,Context context) {
		try {
			String rs = CayThaoLuanInvoike.getCay(idCay);
			if (!rs.trim().equals(Protocol.SERVER_ERROR)) {
				ReadWriteFileController.writeFile(BoardView.treePath, rs);
				return true;
			}
		} catch (Exception e) {
			Toast.makeText(context, "Không thể lấy cây id=" + idCay, 1).show();
			Log.d("Phu", "Không thể lấy cây id=" + idCay);
			return false;
		}
		return false;
	}
	private String taoCay(int idNhom,int idNguoiDung, String noiDung){
		String rs="";
		try {
			 rs=CayThaoLuanInvoike.taoCayMoi(idNhom, idNguoiDung, noiDung);
			 Log.d("Phu", "Tao cay="+rs);
		} catch (Exception e) {
			Log.d("Phu", "Ko tao cay đc");
			e.printStackTrace();
			rs="";
		}
		return rs;
	}
public static void createMemberFile(){
	CMember member=new CMember();
	member.set_fullName(NetworkController._peer.account.get_Username());
	member.set_ip(NetworkController._peer.account.getId()+"");
	member.set_userName(NetworkController._peer.account.get_Username());		
	ReadWriteFileController.deleteFile(ReadWriteFileController.MEMBER_PATH);		
	ReadWriteFileController.insertMember(ReadWriteFileController.MEMBER_PATH, member);
}
}
